package service;

import common.Message;
import common.MessageType;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.List;

/**
 * @Description: 服务端和客户端保持通信线程类
 * @CreateTime: 2024-02-26  14:47
 * @Author: JAMILA
 * @Version: 1.0
 */

public class ServerConnectClientThread extends Thread {
    private Socket socket;
    private String userId;//连接到服务端的用户id
    private boolean loop=true;//控制run中的while循环

    public ServerConnectClientThread(Socket socket, String userId) {
        this.socket = socket;
        this.userId = userId;
    }

    @Override
    public void run() {
        while (loop) {
            try {
                System.out.println("\n服务端和客户端("+userId+")保持通信，读取数据.....");
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Message message = (Message) ois.readObject();
                //根据message类型，进行不同业务处理
                switch (message.getMesType()){
                    case MessageType.MESSAGE_GET_ONLINE_FRIEND://客户端请求在线用户列表
                        /**
                         * 返回格式：100 200 300 至尊宝
                         */
                        System.out.println(message.getSender()+" 请求在线用户列表");
                        String onlineUsers = ManageClientThreads.getOnlineUsers();
                        //返回message给客户端
                        Message message1 = new Message();
                        message1.setMesType(MessageType.MESSAGE_RET_ONLINE_FRIEND);
                        message1.setContent(onlineUsers);
                        message1.setGetter(message.getSender());

                        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                        oos.writeObject(message1);
                        break;
                    case MessageType.MESSAGE_COMM_MES://普通信息
                    case MessageType.MESSAGE_FILE_MES://文件传输
                        if (ManageClientThreads.isOnline(message.getGetter())){//接收者在线
                            //服务器在文件传输和私聊功能中担任转发的角色
                            ServerConnectClientThread serverConnectClientThread1 = ManageClientThreads.getServerConnectClientThread(message.getGetter());
                            ObjectOutputStream oos1 = new ObjectOutputStream(serverConnectClientThread1.getSocket().getOutputStream());
                            oos1.writeObject(message);
                        }else {//接收者不在线
                            //扩展：如果用户不在线，可以将message保存到数据库，这样可以实现离线留言
                            IMServer.addOfflineMessage(message.getGetter(),message);
                        }

                        break;
                    case MessageType.MESSAGE_TO_ALL_MES://群发信息
                        //服务器在群发功能中担任转发的角色
                        //获取出客户本身外所有在线用户线程
                        List<ServerConnectClientThread> threadList = ManageClientThreads.getAllServerConnectClientThread(message.getSender());
                        for (ServerConnectClientThread thread : threadList) {
                            ObjectOutputStream oos2 = new ObjectOutputStream(thread.getSocket().getOutputStream());
                            oos2.writeObject(message);
                        }
                        break;
                    case MessageType.MESSAGE_CLIENT_EXIT://客户端请求退出系统
                        System.out.println(message.getSender()+" 请求退出系统");
                        //将客户端对应的线程从集合中移除
                        ManageClientThreads.removeServerConnectClientThread(message.getSender());
                        socket.close();
                        loop=false;
                        break;
                }



            } catch (Exception e) {
                e.printStackTrace();
            }

        }


    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }
}
